import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { successResponse, errorResponse } from '@/lib/response';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';

async function handler(req: NextRequest) {
  const authResult = await authenticateRequest(req);
  if (!authResult.success) {
    return errorResponse(authResult.error || '身份验证失败');
  }

  const data = await req.json().catch(() => null);
  const { name } = data || {};

  const where: any = {};
  if (name) {
    where.name = {
      contains: name,
    };
  }

  const categories = await prisma.category.findMany({
    where,
    include: {
      menu: {
        select: {
          name: true,
        },
      },
    },
    orderBy: {
      createdAt: 'desc',
    },
  });

  return successResponse(categories);
}

export const POST = withMiddleware(handler);